<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">上传企业相册</view>
      <view class="nav-right">
        <text class="save-btn" @tap="handleSave">保存</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 相册数量提示 -->
      <view class="photos-count">
        <text class="count-text">已上传 {{ currentPhotos.length }}/10</text>
      </view>

      <!-- 相册选择器 -->
      <view class="photos-picker">
        <!-- 显示现有照片 -->
        <view v-if="currentPhotos.length > 0" class="existing-photos">
          <view class="photos-grid">
            <view 
              v-for="(photo, index) in currentPhotos" 
              :key="index" 
              class="photo-item"
            >
              <image :src="photo" class="photo-image" mode="aspectFill"></image>
              <view class="delete-btn" @tap="deletePhoto(index)">
                <text class="delete-text">×</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 添加照片按钮 -->
        <view v-if="currentPhotos.length < 10" class="add-photo-section">
          <uni-file-picker 
            ref="filePicker"
            :limit="10 - currentPhotos.length" 
            title="选择图片"
            :image-styles="imageStyles"
            :preview-image="false"
            :del-icon="false"
            @select="handleSelect"
            @delete="handleDelete"
            @progress="handleProgress"
            @success="handleSuccess"
            @fail="handleFail"
            @exceed="handleExceed"
          ></uni-file-picker>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { updateCompanyPhotosApi, getCompanyPhotoUploadSignsApi } from "@/api/company.js";
import { uploadFileH5 } from "@/utils/file.js";

// 页面参数
const companyId = ref('');

// 文件选择器引用
const filePicker = ref(null);

// 当前相册照片列表
const currentPhotos = ref([]);

// 图片样式配置
const imageStyles = {
  width: 120,
  height: 120
};

// 页面加载时获取参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.companyId) {
    companyId.value = options.companyId;
  }
  
  if (options.photos) {
    try {
      const photos = decodeURIComponent(options.photos);
      if (photos && typeof photos === 'string') {
        currentPhotos.value = photos.split(',').filter(url => url.trim());
      } else if (Array.isArray(photos)) {
        currentPhotos.value = photos;
      }
    } catch (error) {
      console.error('解析相册数据失败:', error);
    }
  }
});

// 选择文件事件
const handleSelect = async (e) => {
  console.log('选择文件:', e);
  
  // 检查是否超出限制
  const maxCount = 10 - currentPhotos.value.length;
  if (maxCount <= 0) {
    uni.showToast({
      title: "相册已满，无法添加更多照片",
      icon: "none"
    });
    return;
  }
  
  // 获取选择的文件信息
  const selectedFiles = e.tempFiles || [];
  if (selectedFiles.length === 0) return;
  
  try {
    uni.showLoading({ title: "获取上传签名中..." });

    // 获取上传签名
    const uploadSigns = await getCompanyPhotoUploadSignsApi(selectedFiles.length);
    console.log("uploadSigns", uploadSigns);
    
    if (!uploadSigns || !Array.isArray(uploadSigns) || uploadSigns.length !== selectedFiles.length) {
      throw new Error('获取上传签名失败或签名数量不匹配');
    }
    
    uni.showLoading({ title: "上传中..." });
    
    // 使用签名进行直传
    const uploadRes = await Promise.all(
      selectedFiles.map(async (file, index) => {
        const sign = uploadSigns[index];
        const res = await uploadFileWithSign(file.path, sign);
        return res;
      })
    );

    const uploadUrls = uploadRes.filter(res => {
      return res !== null && res !== undefined;
    });
    const failedUploads = uploadRes.filter(res => {
      return res === null || res === undefined;
    });
    
    // 将新上传的照片添加到现有相册中
    if (uploadUrls.length > 0) {
      currentPhotos.value.push(...uploadUrls);
    }
    
    uni.hideLoading();
    
    if (uploadUrls.length > 0) {
      if (failedUploads.length > 0) {
        uni.showToast({
          title: `成功添加${uploadUrls.length}张，${failedUploads.length}张失败`,
          icon: "none"
        });
      } else {
        uni.showToast({
          title: `成功添加${uploadUrls.length}张照片`,
          icon: "success"
        });
      }
    } else {
      uni.showToast({
        title: "所有文件上传失败，请重试",
        icon: "none"
      });
      // 所有文件上传失败时清空选择的文件
      if (filePicker.value) {
        filePicker.value.clearFiles();
      }
    }
  
  } catch (error) {
    uni.hideLoading();
    console.log(error.message);
    
    uni.showToast({
      title: "上传失败，请重试",
      icon: "none",
    });
    
    // 上传失败时清空选择的文件
    if (filePicker.value) {
      filePicker.value.clearFiles();
    }
  }
};

// 删除文件事件
const handleDelete = async (e) => {
  console.log('删除文件:', e);
};

// 删除照片
const deletePhoto = async (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张照片吗？',
    success: async (res) => {
      if (res.confirm) {
        currentPhotos.value.splice(index, 1);
      }
    }
  });
};

// 使用签名上传文件
const uploadFileWithSign = async (filePath, sign) => {
  return await uploadFileH5(filePath, sign);
};

// 保存相册
const handleSave = async () => {
  try {
    if (!companyId.value) {
      uni.showToast({
        title: '公司ID不能为空',
        icon: 'none'
      });
      return;
    }

    // 将照片数组转换为逗号分隔的字符串
    const photosString = currentPhotos.value.join(',');
    
    // 调用更新公司相册接口
    const result = await updateCompanyPhotosApi({
      companyId: companyId.value,
      photos: photosString
    });
    uni.showToast({
        title: '相册保存成功',
        icon: 'success',
        duration: 2000
      });
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        // 发送事件通知编辑页面重新获取数据
        uni.$emit('companyInfoUpdated');
        uni.navigateBack();
      }, 1000);
  } catch (error) {
    console.error('保存相册失败:', error);
    uni.showToast({
      title: '相册保存失败，请重试',
      icon: 'none'
    });
  }
};

// 上传进度事件
const handleProgress = (e) => {
  console.log('上传进度:', e);
};

// 上传成功事件
const handleSuccess = (e) => {
  console.log('上传成功:', e);
  // 主要的上传逻辑已在 handleSelect 中处理
};

// 上传失败事件
const handleFail = (e) => {
  console.log('上传失败:', e);
};

// 超出限制事件
const handleExceed = (e) => {
  uni.showToast({
    title: '最多只能选择10张图片',
    icon: 'none'
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 120rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn {
  font-size: 32rpx;
  color: #007aff;
  font-weight: 500;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
  background-color: rgba(0, 122, 255, 0.1);
  transition: all 0.3s ease;
}

.save-btn:active {
  background-color: rgba(0, 122, 255, 0.2);
}

.container {
  padding: 20rpx;
}

/* 相册数量提示样式 */
.photos-count {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

.count-text {
  font-size: 28rpx;
  color: #007aff;
  font-weight: 500;
}

.photos-picker {
  padding: 0 20rpx;
}

/* 现有照片网格 */
.existing-photos {
  margin-bottom: 30rpx;
}

.photos-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.photo-item {
  position: relative;
  width: 100%;
  aspect-ratio: 1;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #f5f5f5;
}

.photo-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.delete-text {
  color: #fff;
  font-size: 24rpx;
  line-height: 1;
}

/* 添加照片区域 */
.add-photo-section {
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  text-align: center;
}

.add-photo-section :deep(.uni-file-picker__container) {
  justify-content: center;
}

.add-photo-section :deep(.uni-file-picker__lists) {
  display: none;
}
</style>
